﻿using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel.Design.Serialization;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using StudyStationWEBAPI.Model;
using Microsoft.AspNetCore.Routing.Constraints;
using StudyStationWEBAPI.Models;
using System.Globalization;
using Newtonsoft.Json.Schema;
using System.Runtime.InteropServices.WindowsRuntime;
using Nancy.Json;

namespace StudyStationWEBAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class FileController : ControllerBase
    {
        /// <summary>
        /// SeverName:Ubuntu 18.04LTS
        /// Host:106.54.73.13
        /// Port:22
        /// UserName:ubuntu
        /// password:trfyyzzs2020!ABC
        /// SharedDirectoryPath:/home/ubuntu/shared
        /// </summary>
        //共享文件目录路径
        private string sharedPath = "/home/ubuntu/shared";
        //SFTP实例化对象
        private SFTP mySFTP = new SFTP("106.54.73.13", 22, "ubuntu", "trfyyzzs2020!ABC");
        //注入MySQL DataBase
        private StationContext db;
        public FileController(StationContext context)
        {
            this.db = context;
        }
        //获取文件列表 Get:api/file/list
        [HttpGet("list")]
        public IQueryable<StudyResource> GetFileList()
        {
            return db.StudyResources;
        }
        //获取服务器的文件列表并更新数据库
        //有无出现数据库中没有的文件->有则更新
        public bool UpdateDatabase()
        {
            var res = mySFTP.GetFileList(sharedPath);
            //更新数据库中缺漏的文件项
            foreach(StudyResource n in res)
            {
                //查询是否有同名的文件
                var query = db.StudyResources.FirstOrDefault(x=>x.fileName == n.fileName);
                
                if (query==null)//没有这样的文件
                {
                    db.StudyResources.Add(n);//添加文件
                    db.SaveChanges();//保存结果
                }
                else if(query.fileSize!=n.fileSize)
                {
                    query.fileSize = n.fileSize;//修改文件大小
                    db.SaveChanges();//保存结果
                }
            }
            var SeverFilenameList = res.Select(x => x.fileName).ToList();
            //去除数据库中多余的文件项
            //数据库中含有表项而服务器端没有此文件
            db.StudyResources.RemoveRange(
                db.StudyResources.Where(x=> !SeverFilenameList.Contains(x.fileName))
            );
            db.SaveChanges();//保存结果
            return true;
        }
        //上传文件 Post:api/file/upload
        //Example: local path:"E:\A.txt",token
        [HttpPost("Upload")]
        public IActionResult Upload(string localpath,StudyResource studyFile)
        {
            FileInfo uploadFile = new FileInfo(localpath);
            if (uploadFile.Exists)//文件存在
            {
                //匹配路径中的文件名
                var fileName = GetLastPartNameOfPath(localpath);
                //查找是否有同名的文件
                var SameName = db.StudyResources.FirstOrDefault(x => x.fileName == fileName);
                if (SameName != null)
                {
                    return Ok("已存在同名文件");
                }
                else
                {
                    /*
                    //查询上传用户相关信息
                    var username = TokenHelper.DecodeToken(token).user_name;
                    User uploadUser = db.Users.FirstOrDefault(o => o.name == username);
                    //生成新的文件对象(文件名、文件大小、上传的用户名、所属的部门)
                    studyFile = new StudyResource { 
                        fileName = uploadFile.Name, 
                        fileSize = uploadFile.Length,
                        uploaderName = username,
                        department = Department,
                        fileCategory = uploadFile.Extension
                    };
                    */
                    db.StudyResources.Add(studyFile);//加入数据库
                    db.SaveChanges();//保存结果
                    //上传文件到指定的路径
                    if (mySFTP.Put(localpath, sharedPath + $"/{fileName}"))
                        return Ok("上传文件成功");
                    else
                        return BadRequest("下载文件失败");
                }
            }
            return BadRequest();
        }
        //下载文件 Post:api/file/download
        //Example: remoteFilename:"A.txt",local path:"E:\"
        [HttpGet("Download")]
        public IActionResult Download(string remoteFilename,string localPath)
        {
            var remotePath = sharedPath + $"/{remoteFilename}";
            localPath = localPath + remoteFilename;
            if (mySFTP.Get(remotePath, localPath))
                return Ok("下载成功");
            else
                return BadRequest("获取文件失败");
        }
        //利用正则表达式匹配路径中的文件名
        public static string GetLastPartNameOfPath(string path)
        {
            var pattern = @"[^/\\]+[/\\]*$";
            var match = System.Text.RegularExpressions.Regex.Match(path, pattern);
            var name = match.Value;

            pattern = @"[^/\\]+";
            match = System.Text.RegularExpressions.Regex.Match(name, pattern);
            name = match.Value;

            return name;
        }
        //根据Department查询相关的文件 Get: api/file/search/department
        [HttpGet("Search/Department")]
        public IQueryable<StudyResource> GetByDepartment(string Department)
        {
            var query = 
                db.StudyResources.Where(o=>o.department==Department);
            return query;
        }
        //根据关键字查询相关的文件 Get: api/file/search/key
        [HttpGet("Search/Key")]
        public IQueryable<StudyResource> GetByKey(string keyword)
        {
            keyword = keyword.ToLower();
            IQueryable<StudyResource> query =
                db.StudyResources.Where(o => o.fileName.ToLower().Contains(keyword));
            return query;
        }
        //根据后缀查找相关的文件 Get: api/file/search/extension
        [HttpGet("Search/Extension")]
        public IQueryable<StudyResource> GetByExtensions(string Extension)
        {
            var query = db.StudyResources.Where(o => o.fileCategory.Contains(Extension));
            return query;
        }
        [HttpGet("Search")]
        public IQueryable<StudyResource> GetBySpecial(string searchCondition)
        {
            JavaScriptSerializer js = new JavaScriptSerializer();   //实例化一个能够序列化数据的类
            SearchCondition theSearchCondition = js.Deserialize<SearchCondition>(searchCondition);
            IQueryable<StudyResource> query = db.StudyResources;
            if(theSearchCondition.department!=null)
            {
                query = query.Where(o => o.department == theSearchCondition.department);
            }
            if(theSearchCondition.keyword!= null)
            {
                query = query.Where(o => o.fileName.ToLower().Contains(theSearchCondition.keyword));
            }
            if(theSearchCondition.extensions != null)
            {
                query = query.Where(o => theSearchCondition.extensions.Contains(o.fileCategory));
            }
            return query;
        }

    }
}
